package network;

import service.UserService;
import java.io.*;
import java.net.*;
import model.User;
import model.Product;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.List;

/**
 * 商城服务器
 * 负责监听客户端连接，处理请求并返回数据
 */
public class EStoreServer {
    private ServerSocket serverSocket;
    private UserService userService;
    private boolean isRunning;
    private static final int PORT = 8888;

    // 服务器自己管理商品数据
    private List<Product> products = new ArrayList<>();
    // 用户购物车存储：username -> (productId -> quantity)
    private Map<String, Map<String, Integer>> userCarts = new ConcurrentHashMap<>();
    // Session管理：sessionId -> username
    private Map<String, String> sessionUsers = new ConcurrentHashMap<>();

    public EStoreServer() {
        this.userService = new UserService();
        this.isRunning = false;
        initializeSampleProducts(); // 初始化示例商品数据
    }

    /**
     * 初始化示例商品数据
     */
    private void initializeSampleProducts() {
        // 添加一些示例商品
        products.add(new Product("p001", "Java从入门到精通", 99.00, 100));
        products.add(new Product("p002", "高性能MySQL", 128.50, 50));
        products.add(new Product("p003", "颈椎康复指南", 45.00, 200));
        products.add(new Product("p004", "生发秘籍", 88.00, 0));
        products.add(new Product("p005", "上课指南", 66.00, 150));

        // 添加标签
        products.get(0).addTag("热门");
        products.get(0).addTag("新品");
        products.get(1).addTag("数据库");
        products.get(1).addTag("技术");
        products.get(2).addTag("健康");
        products.get(2).addTag("热门");
        products.get(4).addTag("学习");
        products.get(4).addTag("教育");

        System.out.println("初始化了 " + products.size() + " 个商品");
    }

    /**
     * 根据商品ID查找商品
     */
    private Product getProductById(String productId) {
        for (Product product : products) {
            if (product.getId().equals(productId)) {
                return product;
            }
        }
        return null;
    }

    /**
     * 获取所有商品
     */
    private List<Product> getAllProducts() {
        return new ArrayList<>(products);
    }

    /**
     * 获取商品数量
     */
    private int getProductCount() {
        return products.size();
    }

    /**
     * 根据sessionId获取用户
     */
    private User getUserBySession(String sessionId) {
        if (sessionId == null) {
            return null;
        }
        return userService.getUserBySession(sessionId);
    }

    /**
     * 数据备份
     */
    private boolean backupData() {
        try {
            // 这里可以实现数据备份逻辑
            // 比如保存到文件、数据库等
            System.out.println("执行数据备份...");
            return true;
        } catch (Exception e) {
            System.err.println("数据备份失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 保存数据
     */
    private void saveData() {
        try {
            // 这里可以实现数据保存逻辑
            System.out.println("保存数据...");
        } catch (Exception e) {
            System.err.println("数据保存失败: " + e.getMessage());
        }
    }

    /**
     * 启动服务器
     */
    public void start() {
        try {
            serverSocket = new ServerSocket(PORT);
            isRunning = true;
            System.out.println("=== 商城服务器启动成功 ===");
            System.out.println("服务器监听端口: " + PORT);
            System.out.println("等待客户端连接...");

            // 无限循环等待客户端连接
            while (isRunning) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端连接: " + clientSocket.getInetAddress().getHostAddress());

                // 为每个客户端创建新线程处理
                new Thread(() -> handleClient(clientSocket)).start();
            }

        } catch (IOException e) {
            System.err.println("服务器启动失败: " + e.getMessage());
            e.printStackTrace();
        } finally {
            stop();
        }
    }

    /**
     * 处理具体业务请求
     */
    private Object processRequest(String request, String sessionId) {
        try {
            System.out.println("处理请求: " + request + ", sessionId: " + sessionId);

            // 用户认证相关请求
            if (request.startsWith("LOGIN:")) {
                // 登录请求格式: LOGIN:username:password
                String[] parts = request.split(":", 3);
                if (parts.length == 3) {
                    String newSessionId = userService.login(parts[1], parts[2]);
                    if (newSessionId != null) {
                        User user = userService.getUserBySession(newSessionId);
                        // 保存session映射
                        sessionUsers.put(newSessionId, user.getUsername());
                        return "LOGIN_SUCCESS:" + newSessionId + ":" + user.getRole();
                    }
                }
                return "LOGIN_FAILED";

            }
            else if (request.startsWith("REGISTER:")) {
                // 注册请求格式: REGISTER:username:password:role
                String[] parts = request.split(":", 4);
                if (parts.length >= 3) {
                    String role = parts.length == 4 ? parts[3] : "user";
                    boolean success = userService.register(parts[1], parts[2], role);
                    return success ? "REGISTER_SUCCESS" : "REGISTER_FAILED";
                }
                return "REGISTER_FAILED";

            } else if ("LOGOUT".equals(request)) {
                if (sessionId != null) {
                    sessionUsers.remove(sessionId);
                    userService.logout(sessionId);
                }
                return "LOGOUT_SUCCESS";

            } else if ("GET_USER_INFO".equals(request)) {
                User user = getUserBySession(sessionId);
                return user != null ? user : "NOT_LOGGED_IN";

            } else if ("GET_ALL_USERS".equals(request)) {
                if (!userService.hasAdminPermission(sessionId)) {
                    return "PERMISSION_DENIED";
                }
                return userService.getAllUsers(sessionId);

            } else if ("GET_ALL_PRODUCTS".equals(request)) {
                // 商品浏览（公开操作，允许未登录用户访问）
                return getAllProducts();

            } else if ("GET_PRODUCT_COUNT".equals(request)) {
                return getProductCount();

            } else if ("CHECK_LOGIN_STATUS".equals(request)) {
                User currentUser = getUserBySession(sessionId);
                return currentUser != null ? "LOGGED_IN" : "NOT_LOGGED_IN";

            }


            // 在 processRequest 方法中添加以下 case
            else if (request.startsWith("ADD_PRODUCT:")) {
                // 添加商品（管理员功能）
                // 格式: ADD_PRODUCT:id:name:price:stock:sessionId
                String[] parts = request.split(":");
                if (parts.length < 6) {
                    return "INVALID_REQUEST";
                }

                String requestSessionId = parts[5];
                System.out.println("ADD_PRODUCT - 使用sessionId: " + requestSessionId);

                // 检查管理员权限
                if (!userService.hasAdminPermission(requestSessionId)) {
                    return "PERMISSION_DENIED";
                }

                String productId = parts[1];
                String productName = parts[2];
                double price = Double.parseDouble(parts[3]);
                int stock = Integer.parseInt(parts[4]);

                // 检查商品ID是否已存在
                if (getProductById(productId) != null) {
                    return "PRODUCT_ID_EXISTS";
                }

                // 创建新商品并添加到列表
                Product newProduct = new Product(productId, productName, price, stock);
                products.add(newProduct);

                System.out.println("管理员添加新商品: " + newProduct);
                return "ADD_PRODUCT_SUCCESS";

            } else if (request.startsWith("UPDATE_PRODUCT:")) {
                // 修改商品（管理员功能）
                // 格式: UPDATE_PRODUCT:productId:newName:newPrice:newStock:sessionId
                String[] parts = request.split(":");
                if (parts.length < 6) {
                    return "INVALID_REQUEST";
                }

                String requestSessionId = parts[5];
                System.out.println("UPDATE_PRODUCT - 使用sessionId: " + requestSessionId);

                // 检查管理员权限
                if (!userService.hasAdminPermission(requestSessionId)) {
                    return "PERMISSION_DENIED";
                }

                String productId = parts[1];
                String newName = parts[2];
                double newPrice = Double.parseDouble(parts[3]);
                int newStock = Integer.parseInt(parts[4]);

                // 查找商品
                Product product = getProductById(productId);
                if (product == null) {
                    return "PRODUCT_NOT_FOUND";
                }

                // 更新商品信息
                product.setName(newName);
                product.setPrice(newPrice);
                product.setStock(newStock);

                System.out.println("管理员修改商品: " + product);
                return "UPDATE_PRODUCT_SUCCESS";

            } else if (request.startsWith("DELETE_PRODUCT:")) {
                // 删除商品（管理员功能）
                // 格式: DELETE_PRODUCT:productId:sessionId
                String[] parts = request.split(":");
                if (parts.length < 3) {
                    return "INVALID_REQUEST";
                }

                String requestSessionId = parts[2];
                System.out.println("DELETE_PRODUCT - 使用sessionId: " + requestSessionId);

                // 检查管理员权限
                if (!userService.hasAdminPermission(requestSessionId)) {
                    return "PERMISSION_DENIED";
                }

                String productId = parts[1];

                // 查找商品
                Product product = getProductById(productId);
                if (product == null) {
                    return "PRODUCT_NOT_FOUND";
                }

                // 从列表中删除商品
                boolean removed = products.removeIf(p -> p.getId().equals(productId));
                if (removed) {
                    System.out.println("管理员删除商品: " + product);

                    // 同时从所有用户的购物车中删除该商品
                    for (Map<String, Integer> cart : userCarts.values()) {
                        cart.remove(productId);
                    }

                    return "DELETE_PRODUCT_SUCCESS";
                } else {
                    return "DELETE_PRODUCT_FAILED";
                }
            }
            // 在 processRequest 方法中添加以下代码
            else if (request.startsWith("GET_ALL_USERS_INFO")) {
                // 查看所有用户信息（管理员功能）
                String requestSessionId = null;  // 默认使用连接的sessionId

                if (request.contains(":")) {
                    String[] parts = request.split(":");
                    if (parts.length >= 2 && !parts[1].isEmpty()) {
                        requestSessionId = parts[1];  // 使用客户端传递的sessionId
                    }
                }

                System.out.println("GET_ALL_USERS_INFO - 使用sessionId: " + requestSessionId + ", 连接sessionId: " + sessionId);
                if (requestSessionId == null || !userService.hasAdminPermission(requestSessionId)) {
                    System.out.println("GET_ALL_USERS_INFO - 权限不足: " + sessionId);
                    return "PERMISSION_DENIED";
                }
                Map<String, User> users = userService.getAllUsers(requestSessionId);
                System.out.println("GET_ALL_USERS_INFO - 返回用户数量: " + users.size());
                return users;
            }
            else if (request.startsWith("DELETE_USER:")) {
                // 删除用户（管理员功能）
                String[] parts = request.split(":");
                if (parts.length < 2) {
                    return "INVALID_REQUEST";
                }

                String usernameToDelete = parts[1];
                String requestSessionId = sessionId; // 默认使用连接的sessionId
                // 如果请求中包含sessionId，使用请求中的sessionId
                if (parts.length >= 3 && !parts[2].isEmpty()) {
                    requestSessionId = parts[2];
                }

                System.out.println("=== DELETE_USER DEBUG ===");
                System.out.println("DELETE_USER - 尝试删除用户: " + usernameToDelete);
                System.out.println("DELETE_USER - 请求sessionId: " + requestSessionId);
                System.out.println("DELETE_USER - 操作者sessionId: " + sessionId);

                // 获取当前操作者用户信息
                User currentUser = getUserBySession(requestSessionId);
                if (currentUser == null) {
                    System.out.println("DELETE_USER - 操作者未登录, requestSessionId: " + requestSessionId);
                    return "NOT_LOGGED_IN";
                }

                System.out.println("DELETE_USER - 操作者用户名: " + currentUser.getUsername());
                System.out.println("DELETE_USER - 操作者角色: " + currentUser.getRole());

                // 检查管理员权限
                boolean hasPermission = userService.hasAdminPermission(requestSessionId);
                System.out.println("DELETE_USER - hasAdminPermission结果: " + hasPermission);

                if (!hasPermission) {
                    System.out.println("DELETE_USER - 权限不足: " + requestSessionId);
                    return "PERMISSION_DENIED";
                }

                System.out.println("DELETE_USER - 调用userService.deleteUser");
                boolean success = userService.deleteUser(requestSessionId, usernameToDelete);
                System.out.println("DELETE_USER - 删除结果: " + success);
                System.out.println("=== DELETE_USER DEBUG END ===");

                return success ? "DELETE_USER_SUCCESS" : "DELETE_USER_FAILED";
            }
            else if (request.startsWith("ADD_TO_CART:")) {
                // 购物车操作需要登录
                // 格式: ADD_TO_CART:productId:quantity 或 ADD_TO_CART:productId:quantity:sessionId
                String[] parts = request.split(":");
                if (parts.length >= 3) {
                    String productId = parts[1];
                    int quantity = Integer.parseInt(parts[2]);

                    // 确定使用的sessionId：优先使用请求中传递的，如果没有则使用连接中的
                    String requestSessionId = sessionId;
                    if (parts.length >= 4 && !parts[3].isEmpty()) {
                        requestSessionId = parts[3];
                    }else {
                        requestSessionId = sessionId; // 使用连接中的sessionId
                    }

                    User currentUser = getUserBySession(requestSessionId);
                    System.out.println("ADD_TO_CART - 使用sessionId: " + requestSessionId + ", 用户: " + (currentUser != null ? currentUser.getUsername() : "null"));
                    if (currentUser == null) {
                        return "NOT_LOGGED_IN";
                    }

                    // 获取用户购物车
                    Map<String, Integer> cart = userCarts.computeIfAbsent(currentUser.getUsername(), k -> new HashMap<>());

                    // 检查商品是否存在
                    Product product = getProductById(productId);
                    if (product == null) {
                        return "PRODUCT_NOT_FOUND";
                    }

                    // 检查库存
                    if (quantity > product.getStock()) {
                        return "INSUFFICIENT_STOCK:" + product.getStock();
                    }

                    // 添加到购物车
                    cart.put(productId, cart.getOrDefault(productId, 0) + quantity);
                    System.out.println("用户 " + currentUser.getUsername() + " 添加商品 " + productId + " 数量 " + quantity);
                    return "ADD_TO_CART_SUCCESS";
                }
                return "INVALID_REQUEST";

            } else if (request.startsWith("GET_CART")) {
                // 获取购物车需要登录
                // 格式: GET_CART 或 GET_CART:sessionId
                String requestSessionId = sessionId;
                if (request.contains(":")) {
                    String[] parts = request.split(":");
                    if (parts.length >= 2 && !parts[1].isEmpty()) {
                        requestSessionId = parts[1];
                    }
                }

                User currentUser = getUserBySession(requestSessionId);
                System.out.println("GET_CART - 当前用户: " + (currentUser != null ? currentUser.getUsername() : "null"));

                if (currentUser == null) {
                    return "NOT_LOGGED_IN";
                }

                Map<String, Integer> cart = userCarts.get(currentUser.getUsername());
                if (cart == null || cart.isEmpty()) {
                    return new HashMap<String, Integer>();
                }
                return cart;

            } else if (request.startsWith("CHECKOUT")) {
                // 结账需要登录
                // 格式: CHECKOUT 或 CHECKOUT:sessionId
                String requestSessionId = sessionId;
                if (request.contains(":")) {
                    String[] parts = request.split(":");
                    if (parts.length >= 2 && !parts[1].isEmpty()) {
                        requestSessionId = parts[1];
                    }
                }
                System.out.println("CHECKOUT - 使用sessionId: " + requestSessionId + ", 连接sessionId: " + sessionId);

                User currentUser = getUserBySession(requestSessionId);
                if (currentUser == null) {
                    System.out.println("CHECKOUT - 用户未登录");
                    return "NOT_LOGGED_IN";
                }

                System.out.println("CHECKOUT - 当前用户: " + currentUser.getUsername());

                Map<String, Integer> cart = userCarts.get(currentUser.getUsername());
                if (cart == null || cart.isEmpty()) {
                    System.out.println("CHECKOUT - 购物车为空");
                    return "CART_EMPTY";
                }

                // 检查库存是否足够
                for (Map.Entry<String, Integer> entry : cart.entrySet()) {
                    Product product = getProductById(entry.getKey());
                    if (product == null) {
                        return "PRODUCT_NOT_FOUND:" + entry.getKey();
                    }
                    if (entry.getValue() > product.getStock()) {
                        return "INSUFFICIENT_STOCK:" + entry.getKey() + ":" + product.getStock();
                    }
                }

                // 扣减库存
                for (Map.Entry<String, Integer> entry : cart.entrySet()) {
                    Product product = getProductById(entry.getKey());
                    if (product != null) {
                        product.setStock(product.getStock() - entry.getValue());
                        System.out.println("扣减库存 - 商品: " + product.getId() + ", 数量: " + entry.getValue() + ", 剩余库存: " + product.getStock());
                    }
                }

                // 清空购物车
                cart.clear();
                System.out.println("用户 " + currentUser.getUsername() + " 结账成功");
                return "CHECKOUT_SUCCESS";

            } else if (request.startsWith("BACKUP_DATA")) {
                // 数据备份需要管理员权限
                String requestSessionId = sessionId;
                if (request.contains(":")) {
                    String[] parts = request.split(":");
                    if (parts.length >= 2 && !parts[1].isEmpty()) {
                        requestSessionId = parts[1]; // 使用客户端传递的sessionId
                    }
                }

                System.out.println("BACKUP_DATA - 使用sessionId: " + requestSessionId);
                // 检查权限
                if (!userService.hasAdminPermission(requestSessionId)) {
                    return "PERMISSION_DENIED";
                }
                boolean backupResult = backupData();
                return backupResult ? "备份成功" : "备份失败";

            } else if ("SAVE_DATA".equals(request)) {
                // 数据保存需要管理员权限
                String requestSessionId = sessionId;
                if (request.contains(":")) {
                    String[] parts = request.split(":");
                    if (parts.length >= 2 && !parts[1].isEmpty()) {
                        requestSessionId = parts[1];
                    }
                }
                if (!userService.hasAdminPermission(requestSessionId )) {
                    return "PERMISSION_DENIED";
                }
                saveData();
                return "数据保存成功";

            } else if ("EXIT".equals(request)) {
                if (userService.hasAdminPermission(sessionId)) {
                    saveData();
                }
                return "服务器数据已保存";

            } else {
                return "未知请求: " + request;
            }

        } catch (Exception e) {
            System.err.println("处理请求时出错: " + e.getMessage());
            e.printStackTrace();
            return "处理请求时出错: " + e.getMessage();
        }
    }

    /**
     * 处理客户端请求
     */
    private void handleClient(Socket clientSocket) {
        String connectionSessionId = null;

        try (ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
             ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream())) {

            System.out.println("开始处理客户端请求: " + clientSocket.getInetAddress().getHostAddress());

            while (true) {
                // 读取客户端请求
                String request = (String) ois.readObject();
                System.out.println("收到客户端请求: " + request + ", sessionId: " + connectionSessionId);

                // 处理请求并返回响应
                Object response = processRequest(request, connectionSessionId);

                // 如果是登录成功，更新sessionId
                if (response instanceof String && ((String) response).startsWith("LOGIN_SUCCESS:")) {
                    String[] parts = ((String) response).split(":");
                    connectionSessionId = parts[1];
                    System.out.println("更新sessionId: " + connectionSessionId);
                }
                // 如果是注销，清空connectionSessionId
                else if ("LOGOUT_SUCCESS".equals(response)) {
                    connectionSessionId = null;
                    System.out.println("清空connectionSessionId");
                }

                oos.writeObject(response);
                oos.flush();

                System.out.println("请求处理完成: " + request);
            }

        } catch (EOFException e) {
            System.out.println("客户端断开连接: " + clientSocket.getInetAddress().getHostAddress());
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("处理客户端请求时出错: " + e.getMessage());
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                System.err.println("关闭客户端连接时出错: " + e.getMessage());
            }
        }
    }

    /**
     * 停止服务器
     */
    public void stop() {
        isRunning = false;
        try {
            if (serverSocket != null && !serverSocket.isClosed()) {
                serverSocket.close();
            }
            System.out.println("服务器已停止");
        } catch (IOException e) {
            System.err.println("停止服务器时出错: " + e.getMessage());
        }
    }

    /**
     * 主方法 - 启动服务器
     */
    public static void main(String[] args) {
        EStoreServer server = new EStoreServer();

        // 添加关闭钩子，确保服务器退出时保存数据
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("\n正在关闭服务器...");
            server.stop();
        }));

        server.start();
    }
}